<template>
    <div class="container">
        <!-- 搜索栏 -->
        <div class="search-container">
            <template v-if="!isDetail">
                <!-- 普通列表搜索条件（字段名与API接收参数一致） -->
                <input type="text" placeholder="跟单编号" v-model="searchParams.tu_status" class="search-input" />
                <input type="text" placeholder="物料编码" v-model="searchParams.material_code" class="search-input" />
                <input type="text" placeholder="物料名称" v-model="searchParams.tu_Name" class="search-input" />
                <select v-model="searchParams.production_line" class="search-select">
                    <option value="">生产线</option>
                    <option value="1#总装集成线">1#总装集成线</option>
                    <option value="1#底架加工线">1#底架加工线</option>
                </select>
            </template>
            <template v-else>
                <!-- 详情页搜索条件（字段名与API接收参数一致） -->
                <input type="text" placeholder="单据编码" v-model="searchParams.id" class="search-input" />
                <select v-model="searchParams.status" class="search-select">
                    <option value="">单据状态</option>
                    <option value="审核">审核</option>
                </select>
                <select v-model="searchParams.business_status" class="search-select">
                    <option value="">业务状态</option>
                    <option value="系统关闭">系统关闭</option>
                    <option value="正常运行">正常运行</option>
                </select>
            </template>
            <div class="date-range">
                <input type="date" v-model="searchParams.start_date" />
                <span>至</span>
                <input type="date" v-model="searchParams.end_date" />
            </div>
            <button @click="handleSearch" class="search-button">搜索</button>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <button class="btn btn-primary" @click="toggleDetail">
                {{ isDetail ? '返回列表' : '查看详情' }}
            </button>
            <button class="btn btn-success" @click="handleCreate">
                新建生产订单
            </button>
            <button class="btn btn-warning" @click="handleExport">
                导出生产数据
            </button>
            <template v-if="isDetail">
                <button class="btn btn-danger" @click="handleDelete">批量删除</button>
                <button class="btn btn-info" @click="handleApprove">批量审核</button>
                <button class="btn btn-secondary" @click="handleReject">批量反审核</button>
            </template>
        </div>

        <!-- 动态表格 -->
        <template v-if="!isDetail">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>跟单编号</th>
                        <th>订单交期</th>
                        <th>单据编码</th>
                        <th>单据状态</th>
                        <th>物料名称</th>
                        <th>物料编码</th>
                        <th>主计量</th>
                        <th>需求日期</th>
                        <th>生产日期</th>
                        <th>生产线</th>
                        <th>生产数量</th>
                        <th>完工数量</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in tableData" :key="item.id">
                        <td>{{ index + 1 }}</td>
                        <td>{{ item.tu_status }}</td>
                        <td>{{ item.tu_Remark }}</td>
                        <td>{{ item.id }}</td>
                        <td>{{ item.status }}</td>
                        <td>{{ item.tu_Name }}</td>
                        <td>{{ item.material_code }}</td>
                        <td>{{ item.producMaterialPiciName }}</td>
                        <td>{{ item.demand_date }}</td>
                        <td>{{ item.production_date }}</td>
                        <td>{{ item.production_line }}</td>
                        <td>{{ item.proNumber }}</td>
                        <td>{{ item.processNumber }}</td>
                    </tr>
                </tbody>
            </table>
        </template>

        <template v-else>
            <table class="data-table">
                <thead>
                    <tr>
                        <th><input type="checkbox" v-model="isAllChecked" @change="handleAllCheck"></th>
                        <th>单据编码</th>
                        <th>单据日期</th>
                        <th>单据状态</th>
                        <th>业务类型</th>
                        <th>业务状态</th>
                        <th>审核日期</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in detailTableData" :key="item.id">
                        <td><input type="checkbox" v-model="item.isChecked" @change="handleSingleCheck(item)"></td>
                        <td>{{ item.id }}</td>
                        <td>{{ formatDate(item.document_date) }}</td>
                        <td>{{ item.status }}</td>
                        <td>{{ item.business_type }}</td>
                        <td>{{ item.business_status }}</td>
                        <td>{{ formatDate(item.tu_Time) }}</td>
                        <td>
                            <button class="link-btn" @click="updateFile(item.id)">查看详情</button>
                            <button class="link-btn" :disabled="item.status !== '开立'">编辑</button>
                            <button class="link-btn danger" :disabled="item.status !== '草稿'">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </template>

        <!-- 分页组件 -->
        <div class="pagination">
            <span>共{{ searchParams.total_count }}条数据</span>
            <select v-model="searchParams.PageSize" @change="handlePageSizeChange">
                <option value="10">10条/页</option>
                <option value="20">20条/页</option>
                <option value="50">50条/页</option>
                <option value="100">100条/页</option>
            </select>
            <div class="page-control">
                <button 
                    :disabled="searchParams.PageIndex <= 1" 
                    @click="prevPage"
                    class="page-btn"
                >
                    上一页
                </button>
                <span>
                    第 {{ searchParams.PageIndex }} 页 / 共 {{ searchParams.totalPages }} 页
                </span>
                <button 
                    :disabled="searchParams.PageIndex >= searchParams.totalPages" 
                    @click="nextPage"
                    class="page-btn"
                >
                    下一页
                </button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import dayjs from 'dayjs';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { KongaUrl } from '@/axios/axiosHelp';

const router = useRouter();
const isDetail = ref(false);
const tableData = ref([]);
const detailTableData = ref([]);
const isAllChecked = ref(false);

// 搜索参数（与API接收参数完全一致，小写驼峰+正确字段）
const searchParams = ref({
    id: '', // 单据编码（API响应字段：id）
    status: '', // 单据状态（API响应字段：status）
    business_status: '', // 业务状态（API响应字段：business_status）
    tu_status: '', // 跟单编号（API响应字段：tu_status）
    material_code: '', // 物料编码（API响应字段：material_code）
    tu_Name: '', // 物料名称（API响应字段：tu_Name）
    production_line: '', // 生产线（API响应字段：production_line）
    KTime: '', // 开始时间（后端要求参数，格式：YYYY-MM-DD）
    JTime: '', // 结束时间（后端要求参数，格式：YYYY-MM-DD）
    PageIndex: 1, // 分页索引（后端参数名：PageIndex）
    PageSize: 15, // 分页大小
    total_count: 0, // 总数据量
    totalPages: 0 // 总页数
});

// 统一数据加载函数（严格匹配API响应结构）
const loadData = () => {
    // 处理日期格式：将前端date组件值转为后端要求的YYYY-MM-DD
    const kTime = searchParams.value.start_date ? 
        dayjs(searchParams.value.start_date).format('YYYY-MM-DD') : '';
    const jTime = searchParams.value.end_date ? 
        dayjs(searchParams.value.end_date).format('YYYY-MM-DD') : '';

    const params = {
        ...searchParams.value,
        KTime: kTime,
        JTime: jTime,
        PageIndex: searchParams.value.PageIndex,
        PageSize: searchParams.value.PageSize
    };

    // 使用实际测试通过的API地址
    axios.get('https://localhost:7006/api/Process/Allcodes', { params })
        .then(res => {
            if (res.data.code === 210) { // 根据API响应状态码判断成功
                const responseData = res.data.data; // 获取最内层data对象
                if (isDetail.value) {
                    // 初始化复选框状态，确保字段名与API响应一致（如item.id）
                    detailTableData.value = responseData.list.map(item => ({
                        ...item,
                        isChecked: false
                    }));
                } else {
                    tableData.value = responseData.list;
                }
                // 填充分页信息
                searchParams.value.total_count = responseData.totalCount;
                searchParams.value.totalPages = responseData.totalPage;
            } else {
                ElMessage.error(res.data.msg || '数据加载失败');
            }
        })
        .catch(error => {
            ElMessage.error('网络请求失败，请检查连接');
            console.error('API请求错误:', error);
        });
};

// 搜索处理：重置页码并加载数据
const handleSearch = () => {
    searchParams.value.PageIndex = 1;
    loadData();
};

// 视图切换：重置页码并切换视图
const toggleDetail = () => {
    isDetail.value = !isDetail.value;
    searchParams.value.PageIndex = 1;
    loadData();
};

// 分页大小变化：重置页码并加载数据
const handlePageSizeChange = () => {
    searchParams.value.PageIndex = 1;
    loadData();
};

// 上下页处理
const prevPage = () => {
    if (searchParams.value.PageIndex > 1) {
        searchParams.value.PageIndex--;
        loadData();
    }
};

const nextPage = () => {
    if (searchParams.value.PageIndex < searchParams.value.totalPages) {
        searchParams.value.PageIndex++;
        loadData();
    }
};

// 复选框逻辑：全选/单选联动
watch(detailTableData, (newVal) => {
    isAllChecked.value = newVal.every(item => item.isChecked);
}, { deep: true });

const handleAllCheck = () => {
    detailTableData.value.forEach(item => {
        item.isChecked = isAllChecked.value;
    });
};

const handleSingleCheck = (item) => {
    isAllChecked.value = detailTableData.value.every(item => item.isChecked);
};

// 日期格式化：处理API返回的带T日期（如2025-05-06T00:00:00）
const formatDate = (date) => {
    return date ? dayjs(date).format('YYYY-MM-DD') : '-';
};

// 操作按钮逻辑
const handleDelete = () => {
    const checkedItems = detailTableData.value.filter(item => item.isChecked);
    if (checkedItems.length === 0) {
        return ElMessage.warning('请选择要删除的单据');
    }

    ElMessageBox.confirm('确定要删除选中的单据吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        detailTableData.value = detailTableData.value.filter(item => !item.isChecked);
        ElMessage.success('删除成功');
    });
};

const handleApprove = () => {
    const checkedItems = detailTableData.value.filter(item => item.isChecked);
    if (checkedItems.length === 0) {
        return ElMessage.warning('请选择要审核的单据');
    }
    checkedItems.forEach(item => {
        item.status = '审核';
        item.business_status = '正常运行';
        item.tu_Time = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 更新审核时间
    });
    ElMessage.success('审核操作成功');
};

const handleReject = () => {
    const checkedItems = detailTableData.value.filter(item => item.isChecked);
    if (checkedItems.length === 0) {
        return ElMessage.warning('请选择要反审核的单据');
    }
    checkedItems.forEach(item => {
        item.status = '开立';
        item.business_status = '系统关闭';
        item.tu_Time = null; // 清除审核时间
    });
    ElMessage.success('反审核操作成功');
};

// 导出功能（传递当前搜索条件）
const handleExport = () => {
    axios.get('https://localhost:7006/api/Production/ExportOrderList', {
        responseType: 'blob',
        params: searchParams.value
    }).then(res => {
        const filename = `生产数据_${dayjs().format('YYYYMMDD')}.xlsx`;
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }).catch(error => {
        ElMessage.error('导出失败，请重试');
        console.error(error);
    });
};

// 路由跳转
const handleCreate = () => {
    router.push('/ProductionAdd');
};

const updateFile = (id) => {
    router.push(`/ProductionUpdate?id=${id}`);
};

// 初始化加载数据
onMounted(() => {
    loadData();
});

// 监听日期清空：重置时间参数
watch(['searchParams.start_date', 'searchParams.end_date'], () => {
    if (!searchParams.value.start_date && !searchParams.value.end_date) {
        searchParams.value.KTime = '';
        searchParams.value.JTime = '';
    }
});
</script>

<style scoped>
.container {
    padding: 20px;
    background: #f5f7fa;
}

.search-container {
    display: flex;
    flex-wrap: nowrap;
    gap: 12px;
    margin-bottom: 20px;
}

.search-input {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
}

.search-input,
.search-select {
    flex: 1;
    min-width: 200px;
}

.date-range {
    display: flex;
    gap: 10px;
    align-items: center;
}

.search-button {
    padding: 8px 16px;
    background: #409eff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.action-buttons {
    margin-bottom: 20px;
}

.btn {
    padding: 8px 15px;
    border-radius: 4px;
    cursor: pointer;
    margin-right: 10px;
}

/* 按钮颜色样式（与Element Plus一致） */
.btn-primary { background: #409eff; color: white; border-color: #409eff; }
.btn-success { background: #67c23a; color: white; border-color: #67c23a; }
.btn-warning { background: #e6a23c; color: white; border-color: #e6a23c; }
.btn-danger { background: #f56c6c; color: white; border-color: #f56c6c; }
.btn-info { background: #66b1ff; color: white; border-color: #66b1ff; }
.btn-secondary { background: #909399; color: white; border-color: #909399; }

.data-table {
    width: 100%;
    border-collapse: collapse;
    background: white;
    margin-bottom: 20px;
}

.data-table th,
.data-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #e8e8e8;
    text-align: left;
}

.data-table th {
    background: #fafafa;
    font-weight: 500;
}

.pagination {
    display: flex;
    align-items: center;
    gap: 20px;
    padding: 15px;
    background: white;
    border-radius: 4px;
}

.link-btn {
    color: #409eff;
    cursor: pointer;
    background: none;
    border: none;
    padding: 0 5px;
}

.link-btn.danger { color: #f56c6c; }

input[type="checkbox"] {
    transform: scale(1.2);
    margin-right: 5px;
    vertical-align: middle;
}

.page-btn {
    padding: 6px 12px;
    border: 1px solid #e4e7ed;
    color: #606266;
    background: #fff;
    cursor: pointer;
    border-radius: 4px;
}

.page-btn:hover { color: #409eff; border-color: #409eff; }
.page-btn:disabled { color: #c0c4cc; cursor: not-allowed; }
</style>